package com.ruoyi.web.controller.api;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.MimeTypeUtils;
import com.ruoyi.system.domain.estate.Pet;
import com.ruoyi.system.domain.estate.PetVaccine;
import com.ruoyi.system.service.estate.IPetService;
import com.ruoyi.system.service.estate.IPetVaccineService;

/**
 * 宠物管理API Controller
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/api/pet")
public class PetApiController extends BaseController
{
    @Autowired
    private IPetService petService;
    
    @Autowired
    private IPetVaccineService petVaccineService;

    /**
     * 查询当前用户的宠物列表
     */
    @Anonymous
    @GetMapping("/list")
    public AjaxResult list()
    {
        try {
            // 获取当前登录用户ID
            Long userId = SecurityUtils.getUserId();
            
            // 查询用户关联的宠物
            Pet pet = new Pet();
            pet.setResidentId(userId);
            List<Pet> list = petService.selectPetList(pet);
            
            return AjaxResult.success(list);
        } catch (Exception e) {
            return AjaxResult.error("获取宠物列表失败：" + e.getMessage());
        }
    }

    /**
     * 获取宠物详细信息
     */
    @Anonymous
    @GetMapping(value = "/{petId}")
    public AjaxResult getInfo(@PathVariable("petId") Long petId)
    {
        try {
            // 获取当前登录用户ID
            Long userId = SecurityUtils.getUserId();
            
            // 查询宠物信息
            Pet pet = petService.selectPetById(petId);
            
            // 验证宠物是否属于当前用户
            if (pet != null && pet.getResidentId() != null && pet.getResidentId().equals(userId)) {
                return AjaxResult.success(pet);
            } else {
                return AjaxResult.error("无权访问该宠物信息");
            }
        } catch (Exception e) {
            return AjaxResult.error("获取宠物详情失败：" + e.getMessage());
        }
    }

    /**
     * 新增宠物
     */
    @Anonymous
    @PostMapping
    public AjaxResult add(@RequestBody Pet pet)
    {
        try {
            // 获取当前登录用户ID
            Long userId = SecurityUtils.getUserId();
            
            // 设置用户ID
            pet.setResidentId(userId);
            
            // 设置默认值
            pet.setStatus("0"); // 正常状态
            pet.setDelFlag("0"); // 未删除
            
            return toAjax(petService.insertPet(pet));
        } catch (Exception e) {
            return AjaxResult.error("添加宠物失败：" + e.getMessage());
        }
    }

    /**
     * 修改宠物
     */
    @Anonymous
    @PutMapping
    public AjaxResult edit(@RequestBody Pet pet)
    {
        try {
            // 获取当前登录用户ID
            Long userId = SecurityUtils.getUserId();
            
            // 查询宠物信息
            Pet existingPet = petService.selectPetById(pet.getPetId());
            
            // 验证宠物是否属于当前用户
            if (existingPet != null && existingPet.getResidentId() != null && existingPet.getResidentId().equals(userId)) {
                // 设置用户ID，防止修改所属用户
                pet.setResidentId(userId);
                
                return toAjax(petService.updatePet(pet));
            } else {
                return AjaxResult.error("无权修改该宠物信息");
            }
        } catch (Exception e) {
            return AjaxResult.error("修改宠物失败：" + e.getMessage());
        }
    }

    /**
     * 删除宠物
     */
    @Anonymous
    @DeleteMapping("/{petId}")
    public AjaxResult remove(@PathVariable Long petId)
    {
        try {
            // 获取当前登录用户ID
            Long userId = SecurityUtils.getUserId();
            
            // 查询宠物信息
            Pet pet = petService.selectPetById(petId);
            
            // 验证宠物是否属于当前用户
            if (pet != null && pet.getResidentId() != null && pet.getResidentId().equals(userId)) {
                return toAjax(petService.deletePetById(petId));
            } else {
                return AjaxResult.error("无权删除该宠物信息");
            }
        } catch (Exception e) {
            return AjaxResult.error("删除宠物失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取宠物疫苗记录
     */
    @Anonymous
    @GetMapping("/vaccine/list/{petId}")
    public AjaxResult getVaccineList(@PathVariable("petId") Long petId)
    {
        try {
            // 获取当前登录用户ID
            Long userId = SecurityUtils.getUserId();
            
            // 查询宠物信息
            Pet pet = petService.selectPetById(petId);
            
            // 验证宠物是否属于当前用户
            if (pet != null && pet.getResidentId() != null && pet.getResidentId().equals(userId)) {
                // 查询疫苗记录
                PetVaccine petVaccine = new PetVaccine();
                petVaccine.setPetId(petId);
                List<PetVaccine> list = petVaccineService.selectPetVaccineList(petVaccine);
                
                return AjaxResult.success(list);
            } else {
                return AjaxResult.error("无权访问该宠物疫苗记录");
            }
        } catch (Exception e) {
            return AjaxResult.error("获取宠物疫苗记录失败：" + e.getMessage());
        }
    }
    
    /**
     * 添加宠物疫苗记录
     */
    @Anonymous
    @PostMapping("/vaccine")
    public AjaxResult addVaccine(@RequestBody PetVaccine petVaccine)
    {
        try {
            // 获取当前登录用户ID
            Long userId = SecurityUtils.getUserId();
            
            // 查询宠物信息
            Pet pet = petService.selectPetById(petVaccine.getPetId());
            
            // 验证宠物是否属于当前用户
            if (pet != null && pet.getResidentId() != null && pet.getResidentId().equals(userId)) {
                return toAjax(petVaccineService.insertPetVaccine(petVaccine));
            } else {
                return AjaxResult.error("无权为该宠物添加疫苗记录");
            }
        } catch (Exception e) {
            return AjaxResult.error("添加宠物疫苗记录失败：" + e.getMessage());
        }
    }
    
    /**
     * 上传宠物头像
     */
    @Anonymous
    @PostMapping("/avatar/{petId}")
    public AjaxResult uploadAvatar(@PathVariable Long petId, @RequestParam("avatarfile") MultipartFile file) throws Exception
    {
        if (!file.isEmpty())
        {
            try {
                // 获取当前登录用户ID
                Long userId = SecurityUtils.getUserId();
                
                // 查询宠物信息
                Pet pet = petService.selectPetById(petId);
                
                // 验证宠物是否属于当前用户
                if (pet != null && pet.getResidentId() != null && pet.getResidentId().equals(userId)) {
                    // 上传文件路径
                    String avatar = FileUploadUtils.upload(RuoYiConfig.getAvatarPath(), file, MimeTypeUtils.IMAGE_EXTENSION);
                    
                    // 修复：确保路径不包含重复的前缀
                    if (avatar.startsWith("/dev-api")) {
                        avatar = avatar.substring(8); // 移除 "/dev-api" 前缀
                    }
                    
                    // 更新宠物头像
                    pet.setAvatar(avatar);
                    petService.updatePet(pet);
                    
                    AjaxResult ajax = AjaxResult.success();
                    ajax.put("imgUrl", avatar);
                    return ajax;
                } else {
                    return AjaxResult.error("无权为该宠物上传头像");
                }
            } catch (Exception e) {
                return AjaxResult.error("上传宠物头像异常：" + e.getMessage());
            }
        }
        return AjaxResult.error("上传宠物头像不能为空");
    }
} 